package exchange.core;

import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.logging.Logger;

import exchange.util.*;

public class Matcher{
	private static Logger log = Logger.getLogger(Matcher.class.getName());

	public static void match(Order newOrder) {
	
		log.info("New Order: " + newOrder.toString());
		LinkedList<Order> counterpartyList = newOrder.getCounterpartyList();
		Order counterpartyOrder;
		boolean isCounterpartyOrderIsEmpty;
		
		
		synchronized (counterpartyList){
			Iterator<Order> it = counterpartyList.iterator();
			while (it.hasNext()){
				counterpartyOrder = it.next();
				if ( !newOrder.isCounterpartyPriceIsEqualOrBetter( counterpartyOrder ) ) { break; }
				if ( newOrder.isFullFilled() ) { break; }

				isCounterpartyOrderIsEmpty = Deal.makeDeal(newOrder, counterpartyOrder);
				if(isCounterpartyOrderIsEmpty) { it.remove(); }
			}
		}
		
		if ( !newOrder.isFullFilled() ){
			addToList(newOrder);
		}
		
	}
	
	public static void addToList(Order newOrder) {
		LinkedList<Order> list = newOrder.getList();
		
		synchronized (list) {
			list.add(newOrder);
			if (newOrder.isBid()){
				Collections.sort(list);
			} else {
				Collections.sort(list, new Comparator<Order>() {
					@Override
					public int compare(Order o1, Order o2) {
						return (o1.getPrice()>o2.getPrice() ? -1 : (o1==o2 ? 0 : 1));
					}
				});
			}				
		}
		
		log.fine(" Added: " + newOrder.toString() +"\n");
	}
	
}
